import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
/**
 * 
 * @author PUSS1401
 * 
 */
@WebServlet("/Members")
public class servletMembers extends servletBase {
	private static final long serialVersionUID = 1L;
	private final int START = 0;
	private final int USER = 1;
	private final int TIMEREPORT = 2;
	private int state = 0;
	private String chosenMember;
	private int chosenWeek, weekToSign, weekToDelete;
	Database db = new Database();
	private String[] members;
	
	
	/**
	 * A servlet that handles the member page. Extends servletBase. 
	 * First it is checked that an user is logged in and has chosen a project, otherwise the user is redirected to the appropriate page.
	 * Displays all currently members for a specific project. If the user is a "Projektledare",
	 * input forms for changing roles for each member that is not a "Projektledare" are also shown.
	 * 
	 * Each user also refers as a link which displays all timereports belonging to that member. A "Projektledare"
	 * can sign/unsign and delete timereports from that page.
	 * 
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession(true);
		if (session == null) {
			response.sendRedirect("lostSession.html");
			return;
		}
		if (!loggedIn(request)) {
			response.sendRedirect("LogIn");
		} else {
			if ((session.getAttribute("project").equals("noproject"))) {
				response.sendRedirect("Projects");
			} else {
				HtmlGenerator gen = new HtmlGenerator();
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();

				String name = session.getAttribute("name").toString();
				String project = session.getAttribute("project").toString();
				String role = session.getAttribute("role").toString();

				if (request.getQueryString() == null
						|| request.getQueryString().equals("?")
						|| request.getQueryString().equals("")) {
					state = START;
				}

				if (!(request.getQueryString() == null)
						&& request.getQueryString().contains("userPage")) {
					System.out.println(request.getQueryString());
					chosenMember = request.getQueryString().substring(9);
					state = USER;
				}

				if (!(request.getQueryString() == null)
						&& request.getQueryString().contains("weekPage")) {
					System.out.println(request.getQueryString());
					chosenWeek = Integer.parseInt(request.getQueryString()
							.substring(9));
					state = TIMEREPORT;
				}
				if (!(request.getQueryString() == null)
						&& request.getQueryString().contains("weekSign")) {
					// System.out.println(request.getQueryString());
					weekToSign = Integer.parseInt(request.getQueryString()
							.substring(21, 22));
					if (db.signedTR(chosenMember, project, weekToSign)) {
						db.unsignTR(chosenMember, project, weekToSign);
					} else {
						db.signTR(chosenMember, project, weekToSign);
					}
				}

				if (!(request.getQueryString() == null)
						&& request.getQueryString().contains("weekDele")) {
					weekToDelete = Integer.parseInt(request.getQueryString()
							.substring(21, 22));
					db.removeTR(chosenMember, project, weekToDelete);
					state = USER;
				}

				String[] changeRole = request.getParameterValues("changerole");
				if (changeRole != null) {
					int count = 0;
					for (int i = 0; i < members.length; i++) {
						if (!db.getRole(members[i], project).equals(
								"Projektledare")) {
							if (!changeRole[count].equals("na")) {
								if (db.changeRole(members[i], project,
										changeRole[count])) {
								} else {
									out.println("<p>Error: " + members[i]
											+ " not possible to update</p>");
								}
							}
							count++;
						}
					}
				}
				out.print(gen.getTop(name, project, role));
				out.print(gen.getProjMenu());
				if (role.equals("Projektledare")) {
					switch (state) {
					case START:
						members = db.listMembers(project);
						out.println("<table border=" + formElement("1") + ">");
						out.println("<th>Name</th><th>Role</th>");
						String changeRoleURL = "<select name=\"changerole\"><option value=\"na\">-</option><option value=\"2\">Utvecklare</option><option value=\"3\">Systemansvarig</option><option value=\"4\">Testare</option></option><option value=\"5\">Ingen roll</option></select>";
						out.println("<form name=\"changerole\" method=\"get\" id=\"changeRoleForm\">");
						for (int i = 0; i < members.length; i++) {
							String member = members[i];
							if (db.activateUser(member)) {
								String userPageURL = "Members?userPage="
										+ member;
								String userPageCode = "<a href="
										+ formElement(userPageURL) + "> "
										+ member + " </a>";
								out.println("<tr>");
								out.println("<td>" + userPageCode + "</td>");
								out.println("<td>"
										+ db.getRole(member, project) + "</td>");
								if (!(db.getRole(member, project)
										.equals("Projektledare"))) {
									out.println("<td>" + changeRoleURL
											+ "</td>");
								}

								out.println("</tr>");
							}
						}
						out.println("</table>");
						out.println("<br><input type=" + formElement("Submit")
								+ "value=" + formElement("Submit")
								+ "form=\"changeRoleForm\"" + ">");
						break;

					case USER:
						ArrayList<TimeReport> listTR = db.listTR(chosenMember,
								project);

						out.println("<table border=" + formElement("1") + ">");
						out.println("<th>Week</th><th>Signed</th>");

						for (int i = 0; i < listTR.size(); i++) {
							int week = listTR.get(i).getWeek();
							String sign;
							if (listTR.get(i).signed()) {
								sign = "Signed";
							} else {
								sign = "Unsigned";
							}
							String weekPageURL = "Members?weekPage=" + week;
							String weekPageCode = "<a href="
									+ formElement(weekPageURL) + "> " + week
									+ " </a>";
							out.println("<tr>");
							out.println("<td>" + weekPageCode + "</td><td>"
									+ sign + "</td>");
							out.println("</tr>");
						}
						out.println("</table>");
						break;
					case TIMEREPORT:
						out.print(gen.viewTimeReport(db.getTR(chosenMember,
								project, chosenWeek)));
						String signButtonURL = "Members?weekSign=" + chosenWeek;
						String deleteButtonURL = "Members?weekDele="
								+ chosenWeek;
						String trSignStatus;
						if (db.getTR(chosenMember, project, chosenWeek)
								.signed()) {
							trSignStatus = "Unsign";
						} else {
							trSignStatus = "Sign";
						}
						String signButton = "<form action="
								+ formElement(signButtonURL) + "method="
								+ formElement("get") + '>';
						signButton += "<button name="
								+ formElement(signButtonURL) + "type="
								+ formElement("submit") + "value="
								+ formElement("sign") + ">" + trSignStatus
								+ "</button>";
						signButton += "</form>";

						String deleteButton = "<form action="
								+ formElement(deleteButtonURL) + "method="
								+ formElement("get") + '>';
						deleteButton += "<button name="
								+ formElement(deleteButtonURL)
								+ " onclick="
								+ formElement("return confirm('Vill du ta bort denna tidsrapport?')")
								+ "type=" + formElement("submit") + "value="
								+ formElement("sign") + ">Delete</button>";
						deleteButton += "</form>";
						if (db.getTR(chosenMember, project, chosenWeek)
								.signed()) {
							out.print(signButton);
						} else {
							out.print(signButton + deleteButton);
						}

						break;
					}
				} else {
					String [] members = db.listMembers(project);
					String html = "<table>";
					for (int i = 0; i < members.length; i++) {
						String member = members[i];
						if (db.activeUser(member)) {
							html += "<tr><td>" + member + "</td><td>"
									+ db.getRole(member, project)
									+ "</td></tr>";
						}
					}
					html += "</table>";
					out.print(html);
				}
				out.print(gen.getBot());
				out.close();
			}
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

}
